package com.ylbh.modules.goods.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylbh.common.pojo.goods.dto.GoodsDTO;
import com.ylbh.common.pojo.goods.dto.SubGoodsClassDTO;
import com.ylbh.common.pojo.goods.vo.GoodsClassVO;
import com.ylbh.common.pojo.goods.vo.GoodsServiceVO;
import com.ylbh.common.pojo.goods.vo.GoodsTypeVO;
import com.ylbh.common.pojo.goods.vo.SpecIficationVO;
import com.ylbh.common.pojo.goodsclass.vo.ShoppingGoodsClassSpecVO;
import com.ylbh.common.pojo.icon.dto.IconDTO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.goods.mapper.GoodsClassMapper;
import com.ylbh.modules.goods.mapper.ShoppingGoodsMapper;
import com.ylbh.modules.goods.service.GoodsClassService;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 商品分类
 * @author mgh
 */
@Service
public class GoodsClassServiceImpl extends ServiceImpl<GoodsClassMapper, SubGoodsClassDTO> implements GoodsClassService {

    @Autowired
    private GoodsClassMapper goodsClassMapper;
    /**
     * 查询商品分类列表
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils queryGoodsClassList(PageDTO pageDTO) {
        IPage<GoodsClassVO> page = new Query<GoodsClassVO>().getPage(pageDTO);
        List<GoodsClassVO> goodsClassVOS = goodsClassMapper.selectGoodsClassList(page);
        return new PageUtils(page.setTotal(page.getTotal()).setRecords(goodsClassVOS));
    }

    /**
     * 获取商品分类的子分类
     * @param id
     * @return
     */
    @Override
    public List<ShoppingGoodsClassSpecVO> queryGoodsSubClassById(Integer id) {
        return goodsClassMapper.queryGoodsSubClassById(id);
    }

    @Override
    public void add(SubGoodsClassDTO subGoodsClassDTO) {
        if (null != subGoodsClassDTO.getIconUrl() && !StringUtils.isEmpty(subGoodsClassDTO.getIconUrl())) {
            String img = subGoodsClassDTO.getIconUrl().substring(subGoodsClassDTO.getIconUrl().lastIndexOf("/") + 1);
            // 去查询原图片地址
            String primaryImg = goodsClassMapper.selectPrimaryImg(subGoodsClassDTO.getId());
            if (null == primaryImg || !img.equals(primaryImg)) {
                IconDTO iconDTO = new IconDTO();
                iconDTO.setImgName(img);
                iconDTO.setImgPath("consumer/icon");
                iconDTO.setAddTime(new Date());
                // 插入分类的图标
                goodsClassMapper.insertGoodsClassSpecImg(iconDTO);
                if (null != primaryImg) {
                    // 修改图片附件表中记录状态为删除
                    goodsClassMapper.deleteAccStatusBy(subGoodsClassDTO.getId());
                }
                subGoodsClassDTO.setIconAccId(iconDTO.getId().intValue());
            }
        }
        subGoodsClassDTO.setLevel(0);
        goodsClassMapper.save(subGoodsClassDTO);
    }

    @Override
    public void modifyById(SubGoodsClassDTO subGoodsClassDTO) {
        if (null != subGoodsClassDTO.getIconUrl() && !StringUtils.isEmpty(subGoodsClassDTO.getIconUrl())) {
            String img = subGoodsClassDTO.getIconUrl().substring(subGoodsClassDTO.getIconUrl().lastIndexOf("/") + 1);
            // 去查询原图片地址
            String primaryImg = goodsClassMapper.selectPrimaryImg(subGoodsClassDTO.getId());
            if (null == primaryImg || !img.equals(primaryImg)) {
                IconDTO iconDTO = new IconDTO();
                iconDTO.setImgName(img);
                iconDTO.setImgPath("consumer/icon");
                iconDTO.setAddTime(new Date());
                // 插入分类的图标
                goodsClassMapper.insertGoodsClassSpecImg(iconDTO);
                if (null != primaryImg) {
                    // 修改图片附件表中记录状态为删除
                    goodsClassMapper.deleteAccStatusBy(subGoodsClassDTO.getId());
                }
                subGoodsClassDTO.setIconAccId(iconDTO.getId().intValue());
            }
        }
        this.updateById(subGoodsClassDTO);
    }

    /**
     * 根据类型id查询规格列表
     * @param typeId
     * @return
     */
    @Override
    public List<SpecIficationVO> querySpecsListByTypeId(Integer typeId) {
        return goodsClassMapper.selectSpecsListByTypeId(typeId);
    }

    /**
     * 接触规格与分类的绑定关系
     * @param typeId
     * @param specId
     */
    @Override
    public void removeSpecByTypeId(Integer typeId, Integer specId) {
        goodsClassMapper.deleteSpecByTypeId(typeId,specId);
    }

    /**
     * 查询这个分类下没有选择的剩余规格
     * @param id
     * @return
     */
    @Override
    public List<SpecIficationVO> querySpecsList(Integer[] id) {
        return goodsClassMapper.querySpecsList(id);
    }

    /**
     * 对当前分类添加规格
     * @param typeId
     * @param specId
     */
    @Override
    public void addClassSpec(Integer typeId, Integer specId) {
        goodsClassMapper.insertClassSpec(typeId,specId);
    }

    /**
     * 获取商品分类列表
     * @return
     */
    @Override
    public List<GoodsTypeVO> queryGoodsTypeList() {
        return goodsClassMapper.selectGoodsTypeList();
    }

    /**
     * 商品服务列表
     * @param pageDTO
     * @return
     */
    @Override
    public PageUtils queryGoodsServiceList(PageDTO pageDTO) {
        Page<Integer> page = new Page<>(pageDTO.getPage(), pageDTO.getLimit());
        List<GoodsServiceVO> list = goodsClassMapper.selectGoodsService(pageDTO.getKeywords(), page);
        return new PageUtils(new Page<GoodsServiceVO>().setTotal(page.getTotal()).setRecords(list));
    }

    /**
     * 商品服务详情
     * @param id
     * @return
     */
    @Override
    public GoodsServiceVO getGoodsServiceInfoById(String id) {
        return goodsClassMapper.selectGoodsServiceInfoById(id);
    }

    /**
     * 修改商品服务信息
     * @param goodsService
     */
    @Override
    public void modifyGoodsServiceDetailsById(GoodsServiceVO goodsService) {
        goodsService.setUpdateTime(new Date());
        goodsService.setUpdateUserId(ShiroUtils.getUserId().intValue());
        goodsClassMapper.updateGoodsServiceDetailsById(goodsService);
    }

    /**
     * 删除商品服务
     * @param ids
     */
    @Override
    public void removeGoodsServiceByIds(List<String> ids) {
        goodsClassMapper.deleteGoodsServiceByIds(ids);
    }

    /**
     * 新增商品服务
     * @param goodsService
     */
    @Override
    public void addGoodsService(GoodsServiceVO goodsService) {
        goodsService.setId(new IdWorker().nextId());
        goodsService.setCreateTime(new Date());
        goodsService.setCreateUserId(ShiroUtils.getUserId().intValue());
        goodsClassMapper.insertGoodsService(goodsService);
    }

    /**
     * 添加二级分类
     * @param subGoodsClassDTO
     */
    @Override
    public void addSecondLevelClass(SubGoodsClassDTO subGoodsClassDTO) {
        String img = subGoodsClassDTO.getIconUrl().substring(subGoodsClassDTO.getIconUrl().lastIndexOf("/") + 1);
        IconDTO iconDTO = new IconDTO();
        iconDTO.setImgPath("consumer/icon");
        iconDTO.setImgName(img);
        iconDTO.setAddTime(new Date());
        goodsClassMapper.insertGoodsClassSpecImg(iconDTO);
        subGoodsClassDTO.setIconAccId(iconDTO.getId().intValue());
        subGoodsClassDTO.setRecommend(1);
        subGoodsClassDTO.setLevel(1);
        subGoodsClassDTO.setGoodsTypeId(goodsClassMapper.selectGoodsTypeId(subGoodsClassDTO.getParentId()));
        goodsClassMapper.selectSecondLevelClass(subGoodsClassDTO, new Date());
    }

    @Override
    public List<String> queryHNDetails() {
        List<GoodsDTO> list = goodsClassMapper.selectHNAllGoods();
        ArrayList<String> list1 = new ArrayList<>();
        for (GoodsDTO goodsDTO:list) {
            if (!StringUtils.isEmpty(goodsDTO.getGoodsDetails())) {
                // 过滤图片
//                Document parse = Jsoup.parse(goodsDTO.getGoodsDetails());
////                Elements imgs = parse.getElementsByTag("img");
////                for (Element img : imgs) {
////                    String src = img.attr("src");
////                    try {
////                        URL urlStr = new URL(src);
////                        HttpURLConnection connection = (HttpURLConnection) urlStr.openConnection();
////                        int state = connection.getResponseCode();
////                        if (state == 200) {
////                            System.out.println("====1====");
////                        } else {
////                            System.out.println("====2====");
////                            list1.add(goodsDTO.getGoodsSerial());
////                            break;
////                        }
////                    } catch (Exception e) {
////                        // TODO: handle exception
////                    }
////                }
                String img = "";
                Pattern p_image;
                Matcher m_image;
                List<String> pics = new ArrayList<String>();

                String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
                p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
                m_image = p_image.matcher(goodsDTO.getGoodsDetails());
                while (m_image.find()) {
                    img = img + "," + m_image.group();
                    // Matcher m =
                    // Pattern.compile("src=\"?(.*?)(\"|>|\\s+)").matcher(img); //匹配src
                    Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);

                    while (m.find()) {
                        pics.add(m.group(1));
                    }
                }
                HashSet hashSet = new HashSet(pics);
                pics.clear();
                pics.addAll(hashSet);
                for (String src:pics) {
                    try {
                        URL urlStr = new URL(src);
                        HttpURLConnection connection = (HttpURLConnection) urlStr.openConnection();
                        int state = connection.getResponseCode();
                        if (state == 200) {
                            System.out.println("====1====");
                        } else {
                            System.out.println("====2====");
                            list1.add(goodsDTO.getGoodsSerial());
                            break;
                        }
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }

            }

        }
        return list1;
    }

}
